import React, { useState, useEffect } from 'react';
import {
  Button,
  Input,
  Label,
  Text,
  Spinner,
  Table,
  TableHeader,
  TableRow,
  TableHead,
  TableBody,
  TableCell,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose
} from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';

// 市场部接口定义
interface MarketDepartment {
  id: number;
  name: string;
  manager: string;
}

// 监听器接口
interface Listener {
  id: string;
  callback: () => void;
}

// 数据管理器类
class DashboardDataManager {
  private listeners: Listener[] = [];
  private static instance: DashboardDataManager | null = null;

  private constructor() {}

  static getInstance(): DashboardDataManager {
    if (!DashboardDataManager.instance) {
      DashboardDataManager.instance = new DashboardDataManager();
    }
    return DashboardDataManager.instance;
  }

  addListener(id: string, callback: () => void): void {
    this.listeners.push({ id, callback });
  }

  removeListener(id: string): void {
    this.listeners = this.listeners.filter(listener => listener.id !== id);
  }

  notifyListeners(): void {
    this.listeners.forEach(listener => listener.callback());
  }
}

// 初始市场部数据
const initialDepartments: MarketDepartment[] = [
  { id: 1, name: '辽冀市场部', manager: '张三' },
  { id: 2, name: '保仓市场部', manager: '李四' },
  { id: 3, name: '黑吉市场部', manager: '王五' },
];

// 从localStorage获取市场部数据
const getMarketDepartments = (): Promise<MarketDepartment[]> => {
  return new Promise((resolve) => {
    const savedDepartments = localStorage.getItem('marketDepartments');
    if (savedDepartments) {
      resolve(JSON.parse(savedDepartments));
    } else {
      // 如果没有保存的数据，返回初始数据并保存
      localStorage.setItem('marketDepartments', JSON.stringify(initialDepartments));
      resolve(initialDepartments);
    }
  });
};

// 添加市场部
const addMarketDepartment = async (department: Omit<MarketDepartment, 'id'>): Promise<void> => {
  const departments = await getMarketDepartments();
  const newId = departments.length > 0 ? Math.max(...departments.map(d => d.id)) + 1 : 1;
  const newDepartment = { ...department, id: newId };
  departments.push(newDepartment);
  localStorage.setItem('marketDepartments', JSON.stringify(departments));
  
  // 通知监听器
  DashboardDataManager.getInstance().notifyListeners();
};

// 更新市场部
const updateMarketDepartment = async (id: number, updates: Partial<MarketDepartment>): Promise<void> => {
  const departments = await getMarketDepartments();
  const index = departments.findIndex(d => d.id === id);
  if (index !== -1) {
    departments[index] = { ...departments[index], ...updates };
    localStorage.setItem('marketDepartments', JSON.stringify(departments));
    
    // 通知监听器
    DashboardDataManager.getInstance().notifyListeners();
  }
};

// 删除市场部
const deleteMarketDepartment = async (id: number): Promise<void> => {
  const departments = await getMarketDepartments();
  const filteredDepartments = departments.filter(d => d.id !== id);
  localStorage.setItem('marketDepartments', JSON.stringify(filteredDepartments));
  
  // 通知监听器
  DashboardDataManager.getInstance().notifyListeners();
};

const dashboardDataManager = DashboardDataManager.getInstance();

const MarketDepartmentManagementPage: React.FC = () => {
  const { session } = useSession();
  const [departments, setDepartments] = useState<MarketDepartment[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentDepartment, setCurrentDepartment] = useState<MarketDepartment | null>(null);
  const [isAddOpen, setIsAddOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [form, setForm] = useState({
    name: '',
    manager: ''
  });
  const [alert, setAlert] = useState('');
  const [showAlert, setShowAlert] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');

  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [selectedDepartments, setSelectedDepartments] = useState<number[]>([]);
  const [selectAll, setSelectAll] = useState(false);

  // 权限检查
  const canEdit = session?.userRole === 'admin' || session?.userRole === 'user';
  const canDelete = session?.userRole === 'admin';
  const canAdd = session?.userRole === 'admin';

  useEffect(() => {
    loadDepartments();
  }, []);

  // 加载市场部列表
  const loadDepartments = async () => {
    setLoading(true);
    try {
      const departmentsData = await getMarketDepartments();
      setDepartments(departmentsData);
    } catch (error) {
      console.error('加载市场部列表失败:', error);
      setAlert('加载市场部列表失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: value }));
  };

  // 重置表单
  const resetForm = () => {
    setForm({
      name: '',
      manager: ''
    });
  };

  // 打开添加对话框
  const handleAddOpen = () => {
    resetForm();
    setIsAddOpen(true);
  };

  // 打开编辑对话框
  const handleEditOpen = (department: MarketDepartment) => {
    setCurrentDepartment(department);
    setForm({
      name: department.name,
      manager: department.manager
    });
    setIsEditOpen(true);
  };

  // 打开删除对话框
  const handleDeleteOpen = (department: MarketDepartment) => {
    setCurrentDepartment(department);
    setIsDeleteOpen(true);
  };

  // 处理添加市场部
  const handleAdd = async () => {
    try {
      await addMarketDepartment({
        name: form.name,
        manager: form.manager
      });
      await loadDepartments();
      setIsAddOpen(false);
      setAlert('添加市场部成功');
      setShowAlert(true);
      setCurrentPage(1);
    } catch (error) {
      console.error('添加市场部失败:', error);
      setAlert('添加市场部失败');
      setShowAlert(true);
    }
  };

  // 处理编辑市场部
  const handleEdit = async () => {
    if (!currentDepartment) return;
    try {
      await updateMarketDepartment(currentDepartment.id, {
        name: form.name,
        manager: form.manager
      });
      await loadDepartments();
      setIsEditOpen(false);
      setAlert('编辑市场部成功');
      setShowAlert(true);
    } catch (error) {
      console.error('编辑市场部失败:', error);
      setAlert('编辑市场部失败');
      setShowAlert(true);
    }
  };

  // 处理删除市场部
  const handleDelete = async () => {
    if (!currentDepartment) return;
    try {
      await deleteMarketDepartment(currentDepartment.id);
      await loadDepartments();
      setIsDeleteOpen(false);
      setAlert('删除市场部成功');
      setShowAlert(true);
      if (getPagedDepartments().length === 0 && currentPage > 1) {
        setCurrentPage(prev => prev - 1);
      }
    } catch (error) {
      console.error('删除市场部失败:', error);
      setAlert('删除市场部失败');
      setShowAlert(true);
    }
  };

  // 处理批量删除
  const handleBatchDelete = async () => {
    if (selectedDepartments.length === 0) {
      setAlert('请先选择要删除的市场部');
      setShowAlert(true);
      return;
    }

    try {
      setLoading(true);
      const deletePromises = selectedDepartments.map(id => deleteMarketDepartment(id));
      await Promise.all(deletePromises);
      await loadDepartments();
      setAlert(`成功删除了 ${selectedDepartments.length} 个市场部`);
      setShowAlert(true);
      setSelectedDepartments([]);
      setSelectAll(false);
      if (getPagedDepartments().length === 0 && currentPage > 1) {
        setCurrentPage(prev => prev - 1);
      }
    } catch (error) {
      console.error('批量删除市场部失败:', error);
      setAlert('批量删除市场部失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 处理选择
  const handleDepartmentSelect = (id: number, checked: boolean) => {
    if (checked) {
      setSelectedDepartments(prev => [...prev, id]);
    } else {
      setSelectedDepartments(prev => prev.filter(deptId => deptId !== id));
    }
  };

  // 处理全选
  const handleSelectAll = () => {
    if (selectAll) {
      setSelectedDepartments([]);
      setSelectAll(false);
    } else {
      const currentPageDepartmentIds = getPagedDepartments().map(dept => dept.id);
      setSelectedDepartments(currentPageDepartmentIds);
      setSelectAll(true);
    }
  };

  // 过滤市场部列表
  const filteredDepartments = departments.filter(dept => 
    dept.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    dept.manager.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // 计算分页数据
  const getPagedDepartments = () => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredDepartments.slice(startIndex, startIndex + itemsPerPage);
  };

  // 计算总页数
  const totalPages = Math.ceil(filteredDepartments.length / itemsPerPage);

  // 分页控制函数
  const goToPage = (page: number) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
      setSelectAll(false);
    }
  };

  const prevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(prev => prev - 1);
      setSelectAll(false);
    }
  };

  const nextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage(prev => prev + 1);
      setSelectAll(false);
    }
  };

  // 处理每页显示数量变化
  const handleItemsPerPageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newItemsPerPage = parseInt(e.target.value);
    setItemsPerPage(newItemsPerPage);
    setCurrentPage(1);
    setSelectedDepartments([]);
    setSelectAll(false);
  };

  // 处理搜索变化
  const handleSearchChange = () => {
    setCurrentPage(1);
    setSelectedDepartments([]);
    setSelectAll(false);
  };

  return (
    <div className="p-6 bg-white">
      {/* 页面标题和操作按钮 */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6 gap-4">
        <Text className="text-2xl font-bold text-gray-900">市场部管理</Text>
        <div className="flex items-center gap-3">
          <div className="relative">
            <Input
              type="text"
              placeholder="搜索市场部名称或负责人..."
              value={searchTerm}
              onChange={(e) => {
                setSearchTerm(e.target.value);
                handleSearchChange();
              }}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            <span className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">🔍</span>
          </div>
          {canDelete && selectedDepartments.length > 0 && (
            <Button variant="destructive" onClick={handleBatchDelete}>
              批量删除 ({selectedDepartments.length})
            </Button>
          )}
          {canAdd && (
            <Button variant="primary" onClick={handleAddOpen}>
              添加市场部
            </Button>
          )}
        </div>
      </div>

      {/* 警告提示 */}
      {showAlert && (
        <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md relative">
          <Text className="text-blue-700">{alert}</Text>
          <Button 
            variant="text" 
            size="sm" 
            onClick={() => setShowAlert(false)}
            className="absolute right-3 top-2 text-blue-500"
          >
            ×
          </Button>
        </div>
      )}

      {/* 市场部列表表格 */}
      <div className="overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              {canDelete && (
                <TableHead className="w-12">
                  <input
                    type="checkbox"
                    checked={selectAll && getPagedDepartments().length > 0}
                    onChange={handleSelectAll}
                    disabled={getPagedDepartments().length === 0}
                    className="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
                  />
                </TableHead>
              )}
              <TableHead className="w-16">ID</TableHead>
              <TableHead>市场部名称</TableHead>
              <TableHead>负责人</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={canDelete ? 5 : 4} className="text-center py-8">
                  <Spinner className="mx-auto" />
                </TableCell>
              </TableRow>
            ) : filteredDepartments.length === 0 ? (
              <TableRow>
                <TableCell colSpan={canDelete ? 5 : 4} className="text-center py-8">
                  暂无市场部数据
                </TableCell>
              </TableRow>
            ) : (
              getPagedDepartments().map((department) => (
                <TableRow key={department.id}>
                  {canDelete && (
                    <TableCell>
                      <input
                        type="checkbox"
                        checked={selectedDepartments.includes(department.id)}
                        onChange={(e) => handleDepartmentSelect(department.id, e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
                      />
                    </TableCell>
                  )}
                  <TableCell>{department.id}</TableCell>
                  <TableCell>{department.name}</TableCell>
                  <TableCell>{department.manager}</TableCell>
                  <TableCell>
                    <div className="flex space-x-2">
                      {canEdit && (
                        <Button variant="text" onClick={() => handleEditOpen(department)}>
                          编辑
                        </Button>
                      )}
                      {canDelete && (
                        <Button variant="text" color="red" onClick={() => handleDeleteOpen(department)}>
                          删除
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 分页控制 */}
      {!loading && filteredDepartments.length > 0 && (
        <div className="flex flex-col md:flex-row md:items-center md:justify-between mt-6 gap-4">
          <div className="flex items-center gap-2">
            <Text>每页显示：</Text>
            <select
              value={itemsPerPage}
              onChange={handleItemsPerPageChange}
              className="px-3 py-1 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
            >
              <option value={5}>5</option>
              <option value={10}>10</option>
              <option value={20}>20</option>
              <option value={50}>50</option>
            </select>
            <Text>
              共 {filteredDepartments.length} 条记录，第 {currentPage} 页，共 {totalPages} 页
            </Text>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              onClick={prevPage}
              disabled={currentPage === 1}
              size="sm"
            >
              上一页
            </Button>
            <div className="flex items-center gap-1">
              {/* 显示页码按钮 */}
              {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                return (
                  <Button
                    key={i + 1}
                    variant={currentPage === i + 1 ? "default" : "outline"}
                    onClick={() => goToPage(i + 1)}
                    size="sm"
                  >
                    {i + 1}
                  </Button>
                );
              })}
              {/* 如果页数超过5页，显示省略号和最后一页 */}
              {totalPages > 5 && (
                <>
                  <Text className="px-2">...</Text>
                  <Button
                    variant={currentPage === totalPages ? "default" : "outline"}
                    onClick={() => goToPage(totalPages)}
                    size="sm"
                  >
                    {totalPages}
                  </Button>
                </>
              )}
            </div>
            <Button
              variant="outline"
              onClick={nextPage}
              disabled={currentPage === totalPages}
              size="sm"
            >
              下一页
            </Button>
          </div>
        </div>
      )}

      {/* 添加市场部对话框 */}
      <Dialog open={isAddOpen} onOpenChange={setIsAddOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>添加市场部</DialogTitle>
            <DialogDescription>
              请填写市场部信息
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="name" className="text-right">市场部名称</Label>
              <Input
                id="name"
                name="name"
                value={form.name}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="manager" className="text-right">负责人</Label>
              <Input
                id="manager"
                name="manager"
                value={form.manager}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button onClick={handleAdd}>添加</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 编辑市场部对话框 */}
      <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>编辑市场部</DialogTitle>
            <DialogDescription>
              请修改市场部信息
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-name" className="text-right">市场部名称</Label>
              <Input
                id="edit-name"
                name="name"
                value={form.name}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-manager" className="text-right">负责人</Label>
              <Input
                id="edit-manager"
                name="manager"
                value={form.manager}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button onClick={handleEdit}>保存</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除市场部对话框 */}
      <Dialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>删除市场部</DialogTitle>
            <DialogDescription>
              确定要删除这个市场部的信息吗？此操作不可撤销。
            </DialogDescription>
          </DialogHeader>
          {currentDepartment && (
            <div className="py-4">
              <Text>市场部名称：{currentDepartment.name}</Text>
              <Text>负责人：{currentDepartment.manager}</Text>
            </div>
          )}
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button variant="destructive" onClick={handleDelete}>
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default MarketDepartmentManagementPage;